if 逻辑判断

        在 shell 脚本中可以使用 if 逻辑判断,只不过它在 shell 中的语法有点奇怪。

1.不带 else

        格式如下:

1
2
3
if 判断语句;then
command
fi

        例如

1
[root@192 sbin]# vim if1.sh

        加入内容:

1
2
3
4
5
6
#!/bin/bash
read -p "Please input your scor:" a
if((a-lt60))
then
echo "You didn' pass the exam."
fi

        在 if1.sh 中出现了 ((a -lt 60)) 这样的形式,这是 shell 脚本中特有的格式,他等于 if[$a-lt60] ,用一个小括号或者不用都会报错,需要记住这个格式。执行结果为:

1
[root@192 sbin]# sh if1.sh

2.带有 else

        格式如下:

1
2
3
4
5
if 判断语句;then
command
else
command
fi

        例如:

1
[root@192 sbin]# vim if2.sh

        加入内容:

1
2
3
4
5
6
7
8
#!/bin/bash
read -p "Please input your score:" a
if((a<60))
then
echo "You didn't pass the exam."
else
echo "Good! You passed the exam."
fi

        执行结果:

1
[root@192 sbin]# sh if2.sh

        和上例唯一区别的地方是,如果输入大于 60 的数字会有提示。

3.带有 elif

        格式如下:

1
2
3
4
5
6
7
if 判断语句;then
command
elif 判断语句二;then
command
else
command
fi

        例如:

1
[root@192 sbin]# vim if3.sh

        加入内容:

1
2
3
4
5
6
7
8
9
10
11
#!/bin/bash
read -p "Please input your score:" a
if ((a<60))
then
echo "You didn't pass the exam."
elif ((a>=60))&&((a<85))
then
echo "Good! You pass the exam."
else
echo "very good! Your score is very high!"
fi

        这里的 && 表示 “并且” 的意思,当然也可以使用 || 表示 “或者”

        执行结果为:

1
[root@192 sbin]# sh if3.sh

        在判断数值大小除了可以用 (()) 的形式外,还可以用 [] 但是就不能使用 > 、<、= 这样的符号了,要使用 -lt (小于),-gt(大于),-le(小于等于),-ge(大于等于),-eq(等于),-ne(不等于)。

        下面以命令行的形式简单比较

1
2
3
4
5
6
7
8
[root@192 sbin]# a=10;if [ $a -lt 5 ];then echo ok;fi
[root@192 sbin]# a=10;if [ $a -gt 5 ];then echo ok;fi
ok
[root@192 sbin]# a=10;if [ $a -ge 10 ];then echo ok;fi
ok
[root@192 sbin]# a=10;if [ $a -eq 10 ];then echo ok;fi
ok
[root@192 sbin]# a=10;if [ $a -ne 10 ];then echo ok;fi

        再看看 if 中使用 && 和 || 的情况:

1
2
3
4
[root@192 sbin]# a=10;if [ $a -lt 1 ]||[ $a -gt 5 ];then echo ok;fi
ok
[root@192 sbin]# a=10;if [ $a -gt 1 ]||[ $a -lt 10 ];then echo ok;fi
ok